package org.example.project_12.controller;

import jakarta.servlet.http.HttpSession;
import org.example.project_12.dto.DocumentDto;
import org.example.project_12.dto.SpaceDto;
import org.example.project_12.entity.User;
import org.example.project_12.service.DocumentService;
import org.example.project_12.service.SpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private DocumentService documentService;
    @Autowired
    private SpaceService spaceService;

    @GetMapping("")
    public String search(@RequestParam(value = "q", required = false) String q,
                        HttpSession session,
                        Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        List<DocumentDto> docResults = null;
        List<SpaceDto> spaceResults = null;
        if (q != null && !q.trim().isEmpty()) {
            docResults = documentService.searchDocumentsByTitle(q.trim(), user.getId());
            spaceResults = spaceService.searchSpacesByName(q.trim(), user.getId());
        }
        model.addAttribute("docResults", docResults);
        model.addAttribute("spaceResults", spaceResults);
        return "search";
    }
} 